package com.qdsg.ysg.doctor.nurse.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ainemo.sdk.otf.ConnectNemoCallback;
import com.ainemo.sdk.otf.LoginResponseData;
import com.ainemo.sdk.otf.NemoSDK;
import com.ainemo.sdk.otf.NemoSDKInitCallBack;
import com.ainemo.sdk.otf.Settings;
import com.ainemo.sdk.otf.VideoConfig;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.base.BaseFragment;
import com.qdsg.ysg.doctor.nurse.activity.AtyAddCallPerson;
import com.qdsg.ysg.doctor.nurse.activity.AtyHistoryOrderList;
import com.qdsg.ysg.doctor.nurse.activity.AtyNurseOrderList;
import com.qdsg.ysg.doctor.ui.ConsultOrderListActivity;
import com.qdsg.ysg.doctor.ui.adapter.DateAdapter;
import com.qdsg.ysg.doctor.ui.dialog.PoliceCallDialog;
import com.qdsg.ysg.doctor.ui.dialog.UpdateDialog;
import com.qdsg.ysg.doctor.util.AES128;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.TimeUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UIConstants;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.response.BaseResponse;
import com.rest.response.BaseStringResponse;
import com.rest.response.ConsultResponse;
import com.rest.response.ContactFindVO;
import com.rest.response.DateTime;
import com.rest.response.DocScheduleVO;
import com.rest.response.LoginResponse;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LocationUtils;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.PreferencesHelper;

public class HomeNurseFragment extends BaseFragment {
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.care_order_wait_num)
    TextView careOrderWaitNum;
    @BindView(R.id.care_order_wait_linear)
    LinearLayout careOrderWaitLinear;
    @BindView(R.id.care_order_accept_num)
    TextView careOrderAcceptNum;
    @BindView(R.id.care_order_accept_linear)
    LinearLayout careOrderAcceptLinear;
    @BindView(R.id.care_order_history)
    TextView careOrderHistory;
    @BindView(R.id.tv_am_num)
    TextView tvAmNum;
    @BindView(R.id.tv_pm_num)
    TextView tvPmNum;
    @BindView(R.id.iv_police_call)
    ImageView ivPoliceCall;
    @BindView(R.id.rv_date)
    RecyclerView rvDate;
    @BindView(R.id.consult_order_wait_num)
    TextView consultOrderWaitNum;
    @BindView(R.id.consult_order_accept_num)
    TextView consultOrderAcceptNum;
    private ArrayList<DateTime> dateList = new ArrayList<>();

    @SuppressLint("StaticFieldLeak")
    private static HomeNurseFragment homeFragment;
    private DateAdapter dateAdapter;
    public String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private static final int LOCATION_CODE = 301;


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_nurse_home;
    }

    @Override
    protected void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvDate.setLayoutManager(linearLayoutManager);
        dateAdapter = new DateAdapter(mContext, dateList);
        rvDate.setAdapter(dateAdapter);

        dateAdapter.setOnItemClickLitener((view, position) -> {
            getMySchedule(dateList.get(position).docscheduledto);

            for (int i = 0; i < dateList.size(); i++) {
                dateList.get(i).isSelect = false;
            }
            dateList.get(position).isSelect = true;
            dateAdapter.notifyDataSetChanged();
        });
        getLocation();

    }

    @Override
    protected void initData() {
        getDateList();
        String token = PreferencesHelper.getInstance().getString( mContext, "token" );
        xyAccount = PreferencesHelper.getInstance().getString( mContext, "xyAccount" );
        xyPassword = PreferencesHelper.getInstance().getString( mContext, "xyPassword" );
        if (!UtilString.isEmpty( token )) {
            login();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getWaitListCount();
        getOrderListCount();
        getConsultListCount();
        tvName.setText(BaseApplication.name);
        if (!UtilString.isEmpty(BaseApplication.avatar)) {
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, BaseApplication.avatar, imgHead);
        } else {
            if ("女".equals(BaseApplication.sex)) {
                imgHead.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_girl));
            } else {
                imgHead.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_boy));
            }
        }
    }

    @OnClick({R.id.care_order_wait_linear, R.id.care_order_accept_linear, R.id.care_order_history, R.id.iv_police_call,
            R.id.consult_order_history,R.id.consult_order_wait_linear,R.id.consult_order_accept_linear,})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.care_order_wait_linear:
                startActivity(new Intent(mContext, AtyNurseOrderList.class).putExtra("fromWhere", "wait"));
                break;
            case R.id.care_order_accept_linear:
                startActivity(new Intent(mContext, AtyNurseOrderList.class).putExtra("fromWhere", "accept"));
                break;
            case R.id.care_order_history:
                startActivity(AtyHistoryOrderList.class);
                break;
            case R.id.iv_police_call:{
                showCallPersonDialog();
                break;
            }
            //护士角色 - 咨询订单 - 待接单
            case R.id.consult_order_wait_linear:{
                Bundle bundle = new Bundle();
                bundle.putString(UIConstants.IM_FLAG, UIConstants.NURSE_CONSULT_1);
                startActivity(ConsultOrderListActivity.class, bundle);
                break;
            }
            //护士角色 - 咨询订单 - 已接单
            case R.id.consult_order_accept_linear:{
                Bundle bundleOne = new Bundle();
                bundleOne.putString(UIConstants.IM_FLAG, UIConstants.NURSE_CONSULT_2);
                startActivity(ConsultOrderListActivity.class, bundleOne);
                break;
            }
            //护士角色 - 咨询订单 - 历史订单
            case R.id.consult_order_history:{

                Bundle bundleOne = new Bundle();
                bundleOne.putString(UIConstants.IM_FLAG, UIConstants.NURSE_CONSULT_1_N);
                startActivity(ConsultOrderListActivity.class, bundleOne);
                break;
            }
            default:
                break;

        }
    }


    private void getMySchedule(String date) {
        RestProxy.getInstance().getMySchedule(date, new Observer<DocScheduleVO>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(DocScheduleVO docScheduleVO) {
                try {
                    tvAmNum.setText(docScheduleVO.data.morningOrder);
                    tvPmNum.setText(docScheduleVO.data.afternoonOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });

    }

    private void getWaitListCount() {
        RestProxy.getInstance().getWaitListCount(new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseStringResponse baseResponse) {
                try {
                    careOrderWaitNum.setText(baseResponse.data);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });

    }

    private void getConsultListCount(){
        RestProxy.getInstance().getConsultListCount(new Observer<ConsultResponse>(){

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ConsultResponse consultResponse) {
                consultOrderWaitNum.setText(TextUtils.isEmpty(consultResponse.getData().getPendingCount())?"":consultResponse.getData().getPendingCount());
                consultOrderAcceptNum.setText(TextUtils.isEmpty(consultResponse.getData().getProgressCount())?"":consultResponse.getData().getProgressCount());

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getOrderListCount() {
        RestProxy.getInstance().getOrderListCount(new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseStringResponse baseResponse) {
                try {
                    careOrderAcceptNum.setText(baseResponse.data);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });

    }


    private void showCodeDialog(final String url, int isUpdate) {
        UpdateDialog mUpdateDialog = UpdateDialog.newInstance(isUpdate, false);
        mUpdateDialog.show(getChildFragmentManager(), "mUpdateDialog");
        mUpdateDialog.setmListener(new UpdateDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                Intent intent = new Intent();
                intent.setData(Uri.parse(url));//Url 就是你要打开的网址
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent); //启动浏览器
                Objects.requireNonNull(getActivity()).finish();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void getDateList() {
        for (int i = 0; i < 7; i++) {
            Calendar c = Calendar.getInstance();
            DateTime dateTime = new DateTime();
            int day1 = c.get(Calendar.DATE);
            c.set(Calendar.DATE, day1 + i);
            dateTime.date = TimeUtil.getTime(c.getTime());
            dateTime.docscheduledto = TimeUtil.getAllTime(c.getTime());
            dateList.add(dateTime);
        }
        dateList.get(0).isSelect = true;
        getMySchedule(dateList.get(0).docscheduledto);
    }

    /**
     * 先初始化一次
     */
    private void getLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
            } else {
                LocationUtils.getInstance(mContext).setAddressCallback(new LocationUtils.AddressCallback() {
                    @Override
                    public void onGetAddress(Address address) {

                    }

                    @Override
                    public void onGetLocation(double lat, double lng) {

                    }
                });

            }
        } else {
            LocationUtils.getInstance(mContext).setAddressCallback(new LocationUtils.AddressCallback() {
                @Override
                public void onGetAddress(Address address) {

                }

                @Override
                public void onGetLocation(double lat, double lng) {

                }
            });
        }

    }


    private void showCallPersonDialog() {
        RestProxy.getInstance().findContact(new Observer<ContactFindVO>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(ContactFindVO contactFindVO) {

                if (UtilString.isEmpty(contactFindVO.data.contactName1) && UtilString.isEmpty(contactFindVO.data.contactName2) && UtilString.isEmpty(contactFindVO.data.contactName3)) {
                    startActivity(AtyAddCallPerson.class);
                } else {
                    LocationUtils.getInstance(mContext).setAddressCallback(new LocationUtils.AddressCallback() {
                        @Override
                        public void onGetAddress(Address address) {
                            String countryName = address.getCountryName();//国家
                            String adminArea = address.getAdminArea();//省
                            String locality = address.getLocality();//市
                            String subLocality = address.getSubLocality();//区
                            String featureName = address.getFeatureName();//具体地址
                            String subAdminArea = address.getSubAdminArea();//街道
//                String area = adminArea + locality + subLocality + subAdminArea + featureName;

                            PoliceCallDialog mPoliceCallDialog = PoliceCallDialog.newInstance(address);
                            mPoliceCallDialog.show(getChildFragmentManager(), "PoliceCallDialog");
                            mPoliceCallDialog.setmListener((address1, appointmentAddress, name) -> {
                                Map<String, Object> map = new HashMap<>();
                                map.put("address", address1);
                                map.put("appointmentAddress", appointmentAddress);
                                map.put("name", name);
                                RestProxy.getInstance().oneKeyAlarm(map, new Observer<BaseResponse>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(BaseResponse baseResponse) {
                                        try {
                                            ToastUtil.showToastCenter(mContext, "报警成功");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        ToastUtil.onError(mContext, e);
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                            });

                        }

                        @Override
                        public void onGetLocation(double lat, double lng) {
                            LogUtil.e("定位经纬度", lat + "维度" + lng);
                        }
                    });
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == LOCATION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                try {
                    LocationUtils.getInstance(mContext).setAddressCallback(new LocationUtils.AddressCallback() {
                        @Override
                        public void onGetAddress(Address address) {

                        }

                        @Override
                        public void onGetLocation(double lat, double lng) {

                        }
                    });
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static HomeNurseFragment newInstance() {
        if (homeFragment == null) {
            homeFragment = new HomeNurseFragment();
            return homeFragment;
        } else {
            return homeFragment;
        }
    }

    public static void Logout() {
        homeFragment = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocationUtils.AddressCallback addressCallback = LocationUtils.getInstance(mContext).getAddressCallback();
        LocationUtils.getInstance(mContext).removeAddressCallback(addressCallback);

    }

    public static String xyAccount = "";//小鱼账号
    public static String xyPassword = "";//小鱼账号密码
    public static Boolean isXyLogin = false;
    private void login() {
        if (UtilString.isEmpty(xyAccount)) {
            String mPhone = PreferencesHelper.getInstance().getString(mContext, "username");
            String mPassword = PreferencesHelper.getInstance().getString(mContext, "password");
            try {
                RestProxy.getInstance().login(AES128.encryptStringAES(mPhone, "7t3e506jaa10xbd4"), AES128.encryptStringAES(mPassword, "7t3e506jaa10xbd4"), "", new Observer<LoginResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        xyAccount = loginResponse.data.videoAccountDTO.account;
                        xyPassword = loginResponse.data.videoAccountDTO.password;
                        PreferencesHelper.getInstance().set(mContext, "token", loginResponse.data.token);
                        PreferencesHelper.getInstance().set(mContext, "xyAccount", loginResponse.data.videoAccountDTO.account);
                        PreferencesHelper.getInstance().set(mContext, "xyPassword", loginResponse.data.videoAccountDTO.password);
                        RestClient.getInstance().token = loginResponse.data.token;
                        xyLogin();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtil.onError(mContext, e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            xyLogin();
        }
    }

    //小鱼登录
    private void xyLogin() {
        NemoSDK.getInstance().loginXYlinkAccount(BaseApplication.xyAccount, BaseApplication.xyPassword, new ConnectNemoCallback() {

            @Override
            public void onFailed(String s) {
                BaseApplication.isXyLogin = false;
                LogUtil.e("小鱼登陆失败错误码：$errorCode" + s);
            }

            @Override
            public void onSuccess(LoginResponseData loginResponseData, boolean b) {
                BaseApplication.isXyLogin = true;
                LogUtil.e("小鱼登陆成功");
            }

            @Override
            public void onNetworkTopologyDetectionFinished(LoginResponseData loginResponseData) {

            }
        });
    }
}
